package io.finer.erp.jeecg.stock.service.impl;

import io.finer.erp.jeecg.finance.vo.PurchaseOrderEntryVO;
import io.finer.erp.jeecg.finance.vo.PurchaseOrderVO;
import io.finer.erp.jeecg.stock.entity.PurchaseOrder;
import io.finer.erp.jeecg.stock.entity.PurchaseOrderEntry;
import io.finer.erp.jeecg.stock.entity.StkIoBill;
import io.finer.erp.jeecg.stock.mapper.PurchaseOrderEntryMapper;
import io.finer.erp.jeecg.stock.mapper.PurchaseOrderMapper;
import io.finer.erp.jeecg.stock.service.IPurchaseOrderService;
import io.finer.erp.jeecg.stock.vo.PurchaseOrderPage;
import io.finer.erp.jeecg.stock.vo.SupplierPriceVO;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.api.client.util.Maps;
import com.google.common.collect.Lists;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.CalendarUtil;
import cn.hutool.core.date.DateUtil;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import java.util.Calendar;
import java.util.Collection;
import java.util.Date;

/**
 * @Description: 采购单
 * @Author: jeecg-boot
 * @Date:   2021-05-20
 * @Version: V1.0
 */
@Service
public class PurchaseOrderServiceImpl extends ServiceImpl<PurchaseOrderMapper, PurchaseOrder> implements IPurchaseOrderService {

	@Autowired
	private PurchaseOrderMapper purchaseOrderMapper;
	@Autowired
	private PurchaseOrderEntryMapper purchaseOrderEntryMapper;
	
	@Override
	@Transactional
	public void saveMain(PurchaseOrder purchaseOrder, List<PurchaseOrderEntry> purchaseOrderEntryList) {
		purchaseOrderMapper.insert(purchaseOrder);
		if(purchaseOrderEntryList!=null && purchaseOrderEntryList.size()>0) {
			for(PurchaseOrderEntry entity:purchaseOrderEntryList) {
				//外键设置
				entity.setMid(purchaseOrder.getId());
				purchaseOrderEntryMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void updateMain(PurchaseOrder purchaseOrder,List<PurchaseOrderEntry> purchaseOrderEntryList) {
		purchaseOrderMapper.updateById(purchaseOrder);
		
		//1.先删除子表数据
		purchaseOrderEntryMapper.deleteByMainId(purchaseOrder.getId());
		
		//2.子表数据重新插入
		if(purchaseOrderEntryList!=null && purchaseOrderEntryList.size()>0) {
			for(PurchaseOrderEntry entity:purchaseOrderEntryList) {
				//外键设置
				entity.setMid(purchaseOrder.getId());
				purchaseOrderEntryMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void delMain(String id) {
		purchaseOrderEntryMapper.deleteByMainId(id);
		purchaseOrderMapper.deleteById(id);
	}

	@Override
	@Transactional
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			purchaseOrderEntryMapper.deleteByMainId(id.toString());
			purchaseOrderMapper.deleteById(id);
		}
	}

	@Override
	public Result<SupplierPriceVO> getSupplierPrice(String supplierId, String categoryId) {
		Result<SupplierPriceVO> result = new Result<>();
		BigDecimal price = this.purchaseOrderEntryMapper.getSupplierPrice(supplierId, categoryId);
		SupplierPriceVO vo = new SupplierPriceVO();
		vo.setCategoryId(categoryId);
		vo.setPrice(price);
		vo.setSupplierId(supplierId);
		result.setResult(vo);
		return result;
	}

	@Override
	public boolean approve(PurchaseOrderPage orderPage) {
		PurchaseOrder order = getById(orderPage.getId());
		if (order == null) {
			throw new JeecgBootException(String.format("【ID：%s】采购单不存在！", orderPage.getId()));
		}
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		order.setApproverId(sysUser.getUsername());
		order.setIsApproved(1);
		order.setEffectiveTime(new Date());
		order.setBillProcStatus("23");
		updateById(order);
		return Boolean.TRUE;
	}

	@Override
	public IPage<PurchaseOrderVO> getPurchaseOrderList(Page<PurchaseOrderVO> page, HttpServletRequest req) {
		String billNo = req.getParameter("billNo_begin");
		Date beginDate = null;
		Date endDate = null;
		String beginDateStr = req.getParameter("billDate_begin");
		String endDateStr = req.getParameter("billDate_end");
		if (StringUtils.isNotBlank(beginDateStr)) {
			beginDate = DateUtil.parseDate(beginDateStr);
		}
		if (StringUtils.isNotBlank(endDateStr)) {
			endDate = DateUtil.parseDate(endDateStr);
			Calendar calendar = CalendarUtil.calendar(endDate);
			calendar.add(Calendar.DAY_OF_YEAR, 1);
			endDate = calendar.getTime();
		}
		String clerkId = req.getParameter("clerkId");
		String supplierId = req.getParameter("supplierId");
		String isApproved = req.getParameter("isApproved");
		Map<String, Object> map = Maps.newHashMap();
		map.put("clerkId", clerkId);
		map.put("billNo", billNo);
		map.put("supplierId", supplierId);
		map.put("isApproved", isApproved);
		map.put("beginDate", beginDate);
		map.put("endDate", endDate);
		IPage<PurchaseOrderVO> pageList = this.baseMapper.getPurchaseOrderList(page, map);
		List<PurchaseOrderVO> records = pageList.getRecords();
		if(CollUtil.isNotEmpty(records)) {
			List<String> ids = Lists.newArrayList();
			Map<String, PurchaseOrderVO> orderMap = Maps.newHashMap();
			for (PurchaseOrderVO purchaseOrderVO : records) {
				ids.add(purchaseOrderVO.getId());
				orderMap.put(purchaseOrderVO.getId(), purchaseOrderVO);
			}
			map.put("idList", ids);
			List<PurchaseOrderEntryVO> purchaseOrderEntryList = this.baseMapper.getPurchaseOrderEntryList(map);
			if(CollUtil.isNotEmpty(purchaseOrderEntryList)) {
				for (PurchaseOrderEntryVO entry : purchaseOrderEntryList) {
					String mid = entry.getMid();
					PurchaseOrderVO vo = orderMap.get(mid);
					List<PurchaseOrderEntryVO> children = vo.getList();
					if(null == children) {
						children = Lists.newArrayList();
						vo.setList(children);
					}
					children.add(entry);
				}
			}
		}
		return pageList;
	}
	
	@Override
	public List<PurchaseOrderVO> getPurchaseOrderList(HttpServletRequest req) {
		String billNo = req.getParameter("billNo_begin");
		Date beginDate = null;
		Date endDate = null;
		String beginDateStr = req.getParameter("billDate_begin");
		String endDateStr = req.getParameter("billDate_end");
		if (StringUtils.isNotBlank(beginDateStr)) {
			beginDate = DateUtil.parseDate(beginDateStr);
		}
		if (StringUtils.isNotBlank(endDateStr)) {
			endDate = DateUtil.parseDate(endDateStr);
			Calendar calendar = CalendarUtil.calendar(endDate);
			calendar.add(Calendar.DAY_OF_YEAR, 1);
			endDate = calendar.getTime();
		}
		String clerkId = req.getParameter("clerkId");
		String supplierId = req.getParameter("supplierId");
		String isApproved = req.getParameter("isApproved");
		Map<String, Object> map = Maps.newHashMap();
		map.put("clerkId", clerkId);
		map.put("billNo", billNo);
		map.put("supplierId", supplierId);
		map.put("isApproved", isApproved);
		map.put("beginDate", beginDate);
		map.put("endDate", endDate);
		List<PurchaseOrderVO> records = this.baseMapper.getPurchaseOrderList(map);
		if(CollUtil.isNotEmpty(records)) {
			List<String> ids = Lists.newArrayList();
			Map<String, PurchaseOrderVO> orderMap = Maps.newHashMap();
			for (PurchaseOrderVO purchaseOrderVO : records) {
				ids.add(purchaseOrderVO.getId());
				orderMap.put(purchaseOrderVO.getId(), purchaseOrderVO);
			}
			map.put("idList", ids);
			List<PurchaseOrderEntryVO> purchaseOrderEntryList = this.baseMapper.getPurchaseOrderEntryList(map);
			if(CollUtil.isNotEmpty(purchaseOrderEntryList)) {
				for (PurchaseOrderEntryVO entry : purchaseOrderEntryList) {
					String mid = entry.getMid();
					PurchaseOrderVO vo = orderMap.get(mid);
					List<PurchaseOrderEntryVO> children = vo.getList();
					if(null == children) {
						children = Lists.newArrayList();
						vo.setList(children);
					}
					children.add(entry);
				}
			}
		}
		return records;
	}
}
